package com.mrjy.activity.bo;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.lang.ArrayUtils;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mrjy.activity.dao.IActivityInfoDao;
import com.mrjy.activity.dao.IActivitySignupInfoDao;
import com.mrjy.activity.dao.IActivityTypeRelDao;
import com.mrjy.activity.dao.IActivityUserRelDao;
import com.mrjy.activity.dto.ActivityDTO;
import com.mrjy.activity.dto.ActivityInfoDTO;
import com.mrjy.activity.dto.ActivityLiveDTO;
import com.mrjy.activity.dto.ActivityOutputDTO;
import com.mrjy.activity.dto.ActivityOutputPageDTO;
import com.mrjy.activity.dto.ActivitySelectDTO;
import com.mrjy.activity.dto.TeacherDTO;
import com.mrjy.common.entity.ActivityInfo;
import com.mrjy.common.entity.ActivityTypeRel;
import com.mrjy.common.entity.ActivityUserRel;
import com.mrjy.common.entity.PolyInfo;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.enums.ResultEnum;
import com.mrjy.common.exception.InnerException;
import com.mrjy.common.handler.MapResultHandler;
import com.mrjy.common.redis.RedisPool;
import com.mrjy.common.util.ConstantsUtil;
import com.mrjy.common.util.DateUtil;
import com.mrjy.common.util.ExcelUtil;
import com.mrjy.common.util.GlobalConstant;
import com.mrjy.common.util.PolyvTokenUtil;
import com.mrjy.common.util.PolyvUtil;
import com.mrjy.common.util.RedisUtil;
import com.mrjy.common.util.ResultUtil;
import com.mrjy.maintain.util.SharingProportionEnum;
import com.tencent.common.Util;

@Service("activityInfoBo")
public class ActivityInfoBo implements IActivityInfoBo {
	@Resource
	private IActivityInfoDao activityInfoDao;
	@Resource
	private IActivityTypeRelDao activityTypeRelDao;
	@Resource
	private IActivityUserRelDao activityUserRelDao;
	@Resource
	private SqlSessionTemplate sqlSessionTemplate;
	@Resource
	private IActivitySignupInfoDao activitySignupInfoDao;
	@Autowired
	private RedisPool redisPool;
	private static Logger logger = LoggerFactory.getLogger(ActivityInfoBo.class);
	
	@Override
	public Object txInsert(ActivityInfo activityInfo) {
		
		//插入活动,返回自增主键
		activityInfoDao.insert(activityInfo);
		if (null == activityInfo.getId()) {
			logger.error("【新增活动】插入失败, activityInfo={}",activityInfo);
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("err_code", ResultEnum.INSERT_ERROR.getCode());
			map.put("err_code", ResultEnum.INSERT_ERROR.getMessage());
			return  map;
		}
		
		//处理讲师
		Integer[] teachers = activityInfo.getTeachers();
		List<ActivityUserRel> teacherList = new ArrayList<>();
		for (Integer userId : teachers) {
			ActivityUserRel rel = new ActivityUserRel();
			rel.setActivityId(activityInfo.getId());
			rel.setUserId(userId);
			teacherList.add(rel);
		}
		activityUserRelDao.insertBatch(teacherList);
		
		//处理标签
		Integer[] types = activityInfo.getTypes();
		List<ActivityTypeRel> typeList = new ArrayList<>();
		for (Integer typeId : types) {
			ActivityTypeRel rel = new ActivityTypeRel();
			rel.setTypeId(typeId);
			rel.setActivityId(activityInfo.getId());
			typeList.add(rel);
		}
		activityTypeRelDao.insertBatch(typeList);
		if(activityInfo.getVideoCode() != null){//判断该活动是否传了视频
			//添加缓存
			String polyInfoJson = "";
			PolyInfo polyInfo = new PolyInfo();
			/*安全处理判断缓存是否已经存在*/
			String activityVideoId = GlobalConstant.VIDEO_POLYV_URL+activityInfo.getId();
			if(activityVideoId != null){
				redisPool.del(activityVideoId);
			}
			PolyInfo polyInfoVideo = (PolyInfo) PolyvUtil.queryUrlByVid(activityInfo.getVideoCode());
			//封装成一个polyInfo
			if (polyInfoVideo!=null) {
				polyInfo.setMpvh(polyInfoVideo.getMpvh());
				polyInfo.setMpvl(polyInfoVideo.getMpvl());
				polyInfo.setMpvm(polyInfoVideo.getMpvm());
				polyInfo.setImgh(polyInfoVideo.getImgh());
				polyInfo.setImgl(polyInfoVideo.getImgl());
                polyInfo.setMpvFlag(polyInfoVideo.getMpvFlag());
                polyInfo.setHls_l(polyInfoVideo.getHls_l());
                polyInfo.setHls_m(polyInfoVideo.getHls_m());
                polyInfo.setHls_h(polyInfoVideo.getHls_h());
                polyInfo.setSeed(polyInfoVideo.getSeed());
                polyInfo.setDuration(polyInfoVideo.getDuration());
            }
			polyInfoJson = JSONObject.fromObject(polyInfo).toString();
			if (polyInfoJson!=null) {
				redisPool.set(GlobalConstant.VIDEO_POLYV_URL+activityInfo.getId(), JSONObject.fromObject(polyInfoJson).toString());
			}
		}
		return ResultUtil.success();
	}

	@Override
	public Object txUpdate(ActivityInfo activityInfo) {
		
		ActivityInfo oldActivityInfo = activityInfoDao.selectByPrimaryKey(activityInfo.getId());
		//更新活动
		activityInfoDao.updateByPrimaryKeySelective(activityInfo);
		
		if (!ArrayUtils.isEmpty(activityInfo.getTeachers())) {
			//处理讲师
			Integer[] teachers = activityInfo.getTeachers();
			activityUserRelDao.deleteByActivityId(activityInfo.getId());
			List<ActivityUserRel> teacherList = new ArrayList<>();
			for (Integer userId : teachers) {
				ActivityUserRel rel = new ActivityUserRel();
				rel.setActivityId(activityInfo.getId());
				rel.setUserId(userId);
				teacherList.add(rel);
			}
			activityUserRelDao.insertBatch(teacherList);
		}
		
		if (!ArrayUtils.isEmpty(activityInfo.getTypes())) {
			//处理标签
			activityTypeRelDao.deleteByActivityId(activityInfo.getId());
			Integer[] types = activityInfo.getTypes();
			List<ActivityTypeRel> typeList = new ArrayList<>();
			for (Integer typeId : types) {
				ActivityTypeRel rel = new ActivityTypeRel();
				rel.setTypeId(typeId);
				rel.setActivityId(activityInfo.getId());
				typeList.add(rel);
			}
			activityTypeRelDao.insertBatch(typeList);
		}
		//编辑活动删除了视频或者更换了视频(清除缓存)
		if((oldActivityInfo.getVideoCode() != null && activityInfo.getVideoCode()== null) || (oldActivityInfo.getVideoCode() != activityInfo.getVideoCode())){
			String activityVideoId = GlobalConstant.VIDEO_POLYV_URL+activityInfo.getId();
			if(activityVideoId != null){
				redisPool.del(activityVideoId);
			}
			
		}
		if(activityInfo.getVideoCode() != null){//判断该活动是否传了视频
			//添加缓存
			String polyInfoJson = "";
			PolyInfo polyInfo = new PolyInfo();
			PolyInfo polyInfoVideo = (PolyInfo) PolyvUtil.queryUrlByVid(activityInfo.getVideoCode());
			//封装成一个polyInfo
			if (polyInfoVideo!=null) {
				polyInfo.setMpvh(polyInfoVideo.getMpvh());
				polyInfo.setMpvl(polyInfoVideo.getMpvl());
				polyInfo.setMpvm(polyInfoVideo.getMpvm());
				polyInfo.setImgh(polyInfoVideo.getImgh());
				polyInfo.setImgl(polyInfoVideo.getImgl());
                polyInfo.setMpvFlag(polyInfoVideo.getMpvFlag());
                polyInfo.setHls_l(polyInfoVideo.getHls_l());
                polyInfo.setHls_m(polyInfoVideo.getHls_m());
                polyInfo.setHls_h(polyInfoVideo.getHls_h());
                polyInfo.setSeed(polyInfoVideo.getSeed());
                polyInfo.setDuration(polyInfoVideo.getDuration());
            }
			polyInfoJson = JSONObject.fromObject(polyInfo).toString();
			if (polyInfoJson!=null) {
				redisPool.set(GlobalConstant.VIDEO_ACTIVITY_POLYV_URL+activityInfo.getId(), JSONObject.fromObject(polyInfoJson).toString());
			}
		}
		return ResultUtil.success();
	}
	
	@Override
	public Object queryPageBack(ActivitySelectDTO selectDTO) {
		PageHelper.startPage(selectDTO.getPage(), selectDTO.getRows());
		List<ActivityOutputDTO> activityOutputDTOList = activityInfoDao.queryPageBack(selectDTO);
		PageInfo<ActivityOutputDTO> pageInfo = new PageInfo<>(activityOutputDTOList);
		//封装结果集
		ActivityOutputPageDTO result = new ActivityOutputPageDTO();
		//计算总报名人数
		int totalSignup = activityInfoDao.queryTotalSignup(selectDTO);
		
		result.setTotalSignup(totalSignup);
		result.setTotal(new Integer(String.valueOf(pageInfo.getTotal())));
		result.setTotalActivity(result.getTotal());
		result.setRows(activityOutputDTOList);
		return ResultUtil.success(result);
	}
	
	@Override
	public Object export(ActivitySelectDTO selectDTO,HttpServletResponse response) {
		List<ActivityOutputDTO> dataset = activityInfoDao.queryPageBack(selectDTO);
		if (CollectionUtils.isEmpty(dataset)) {
			return ResultUtil.error(ResultEnum.NO_DATA_EXPORT);
		}
		//封装数据
		String type = "";
		for (ActivityOutputDTO activityOutputDTO : dataset) {
			// 1-直播 2-线上 3-线下
			switch (activityOutputDTO.getActivityType()) {
			case "1":
				type = "直播";
				break;
			case "2":
				type = "线上";
				break;
			case "3":
				type = "线下";
			default:
				break;
			}
			activityOutputDTO.setActivityType(type);
		}
		try {
			ExcelUtil.writeExcel(response, "活动"+DateUtil.dateToString(new Date(), DateUtil.FULL_DATE_STR)+".xls", dataset, ActivityOutputDTO.class);
			return ResultUtil.success();
		} catch (Exception e) {
			logger.error("【导出活动】 导出失败,error:{}",e.getMessage());
//			throw new InnerException(ResultEnum.ERROR);
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("err_code", ResultEnum.ERROR.getCode());
			map.put("err_code", ResultEnum.ERROR.getMessage());
			return  map;
		}
	}

	@Override
	public Object queryPage(HttpSession session, Integer page, Integer rows) {
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		PageHelper.startPage(page, rows);
		List<ActivityDTO> activityDTOList = activityInfoDao.queryPage(loginUser==null?0:loginUser.getId());
		return ResultUtil.success(activityDTOList);
	}

	@Override
	public Object queryById(HttpSession session, Integer activityId) {
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		HashMap<String, Object> map = new HashMap<String, Object>();
		//查询基本数据
		if(loginUser == null){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		ActivityInfoDTO activityInfoDTO = activityInfoDao.queryById(activityId);
		//封装数据
		if(activityInfoDTO != null){
			//添加省份和城市到活动地址上去
			if(ConstantsUtil.getProperty("ACTIVITY_TYPE.OFFLINT")
					.equals(activityInfoDTO.getActivityType())){
				String province = activityInfoDTO.getProvince()==null? "":activityInfoDTO.getProvince() ;
				String city = activityInfoDTO.getCity()==null? "":activityInfoDTO.getCity() ;
				activityInfoDTO.setActivityAddress(province	+ city + activityInfoDTO.getActivityAddress());
			}
			//赚XX元 ,这里用活动原价*10%
			activityInfoDTO.setProfit(activityInfoDTO.getOriginalMoneyRequire()
					.multiply(new BigDecimal(SharingProportionEnum.NORMAL.getSharingProportion())).setScale(2, BigDecimal.ROUND_HALF_UP));
			//如果是直播活动,根据时间设置直播状态
			if (ConstantsUtil.getProperty("ACTIVITY_TYPE.LIVE")
					.equals(activityInfoDTO.getActivityType())) {
				Timestamp currentTime = new Timestamp(System.currentTimeMillis());
				Timestamp startTime = activityInfoDTO.getStartTime();
				Timestamp endTime = activityInfoDTO.getEndTime();
				String liveStatus = "";
				if (currentTime.before(startTime)) {
					liveStatus = ConstantsUtil.getProperty("ACTIVITY_LIVE.ADVANCE");
				}else if (currentTime.after(endTime)) {
					liveStatus = ConstantsUtil.getProperty("ACTIVITY_LIVE.PLAYBACK");
				}else {
					liveStatus = ConstantsUtil.getProperty("ACTIVITY_LIVE.ING");
				}
				activityInfoDTO.setLiveStatus(liveStatus);
			}
			int isSignup = 0;
			if (null!=loginUser) {
				isSignup = activitySignupInfoDao.countByUserIdAndActivityId(loginUser.getId(), activityId);
			}
			if (isSignup > 0) {
				//已报名 
				activityInfoDTO.setIsSignup(ConstantsUtil.getProperty("ACTIVITY.SIGNUP"));
			}else {
				//未报名 
				activityInfoDTO.setIsSignup(ConstantsUtil.getProperty("ACTIVITY.NOTSIGNUP"));
			}
			if(activityInfoDTO.getVideoCode() != null){//该活动有宣传视频
				 PolyvTokenUtil tokenUtil = null;
	                try {
	                    tokenUtil = PolyvTokenUtil.cloneSimplePolyInfo(activityInfoDTO.getVideoCode(),null,
	                            Util.getHostIp(Util.getInetAddress()),
	                            loginUser.getId().toString(), "123", "1225");
	                } catch (CloneNotSupportedException e) {
	                    e.printStackTrace();
	                    return "error";
	                }

	                PolyInfo polyInfo = RedisUtil.cacheActivityVideo(activityInfoDTO.getId() + "");
	                if(polyInfo != null){
	                	map.put("polyInfo", polyInfo);
	                	map.put("ts", tokenUtil.getTs());
		                map.put("sign", tokenUtil.getSign());
	                }
			}
			activityInfoDTO.setVideoCode(null);
			map.put("err_code", 0);
			map.put("err_msg", "成功");
			map.put("rows", activityInfoDTO);
			return map;
		}else{
			return ResultUtil.error(402,"没有找到该活动");
		}
		
	}
	
	@Override
	public Object queryLivePage(Integer page, Integer rows) {
		String activityType = ConstantsUtil.getProperty("ACTIVITY_TYPE.LIVE");
		PageHelper.startPage(page, rows);
		List<ActivityLiveDTO> list = activityInfoDao.queryPageByActivityType(activityType);
		if (!CollectionUtils.isEmpty(list)) {
			Integer[] activityIds = new Integer[list.size()];
			for (int i=0;i<list.size();i++) {
				activityIds[i] = list.get(i).getId();
			}
			//查询活动讲师
			MapResultHandler handler = new MapResultHandler();
			//基于接口注入的mybatis配置无法使用自定义ResultHandler
			//activityUserRelDao.queryByActivityId(activityIds, handler);
			//获取数据库连接
			SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession();
			session.select("com.mrjy.activity.dao.IActivityUserRelDao.queryByActivityId",activityIds, handler);
			Map<Integer, List<TeacherDTO>> mappedResults = handler.getMappedResults();
			//封装数据
			Timestamp currentTime = new Timestamp(System.currentTimeMillis());
			
			String liveStatus = "";
			for (ActivityLiveDTO activityLiveDTO : list) {
				for (Entry<Integer, List<TeacherDTO>> entry : mappedResults.entrySet()) {
					if (entry.getKey().intValue()==activityLiveDTO.getId()) {
						activityLiveDTO.setTeachers(entry.getValue());
					}
				}
				Timestamp startTime = activityLiveDTO.getStartTime();
				Timestamp endTime = activityLiveDTO.getEndTime();
				if (currentTime.before(startTime)) {
					liveStatus = ConstantsUtil.getProperty("ACTIVITY_LIVE.ADVANCE");
				}else if (currentTime.after(endTime)) {
					liveStatus = ConstantsUtil.getProperty("ACTIVITY_LIVE.PLAYBACK");
				}else {
					liveStatus = ConstantsUtil.getProperty("ACTIVITY_LIVE.ING");
				}
				activityLiveDTO.setLiveStatus(liveStatus);
			}
		}
		return ResultUtil.success(list);
	}

	@Override
	public Object txDeleteByIds(int[] ids) {
		for(Integer activityId : ids){
			activityTypeRelDao.deleteByActivityId(activityId);
			activityUserRelDao.deleteByActivityId(activityId);
		}
		int row = activityInfoDao.deleteByIds(ids) ;
		if(row > 0){
			return ResultUtil.success() ;
		}else{
			return ResultUtil.error() ;
		}
	}

	@Override
	public Object txUpdateDisableFlag(ActivityInfo info) {
		
		int row = activityInfoDao.updateDisableFlag(info);
		if(row > 0){
			return ResultUtil.success() ;
		}else{
			return ResultUtil.error();
		}
	}

	@Override
	public ActivityInfoDTO queryActivityById(int activityId) {
		// TODO Auto-generated method stub
		ActivityInfoDTO info = activityInfoDao.queryById(activityId);
		return info;
	}
	
}
